﻿var isFileRequest = false;
function setupAjax() {
    // 请求前先设置好antitoken
    $.ajaxSetup({
        beforeSend: function (xhr) {
            xhr.setRequestHeader("RequestVerificationToken",
                $('input:hidden[name="__RequestVerificationToken"]').val());
            if (!isFileRequest) {
                xhr.setRequestHeader("Content-Type", "application/json");
            }
        }
    });
}
setupAjax();

var dataTypes = [];// = JSON.parse('@Html.Raw(Model.DbDataTypes.ToJson())');
var defaultColumns = {};
$(function () {
    //$("select[name=DataType]").select2({
    //    language: 'zh-CN',
    //    width: '100%',
    //    placeholder: '请选择',
    //    //minimumInputLength: 10
    //    data: dataTypes
    //})
    loadDefaultColumns();

    Config.load(0, '.main-config', o => setCurrentDbType(o.DbType, true), () => setDefaultConnectInfo(0));

    // 注册新行动作
    regRowAction();

    $("#btnSetConfig").on("click", e => {
        setConfig();
    });

    var defaultColumnNameOp = new DefaultColumnNameOper();
    $(".add-col").on('click', e => {
        var type = parseInt($("select[name=DefaultColumnNameType]").val());
        //console.log("type:" + type);
        items = defaultColumnNameOp.checkName(defaultColumns.createColumn, type);
        //console.log(items);
        addDefaultColumnRow(items);
    });
    $(".mod-col").on('click', e => {
        var type = parseInt($("select[name=DefaultColumnNameType]").val());
        addDefaultColumnRow(defaultColumnNameOp.checkName(defaultColumns.modifyColumn, type));
    });
    $(".del-col").on('click', e => {
        var type = parseInt($("select[name=DefaultColumnNameType]").val());
        addDefaultColumnRow(defaultColumnNameOp.checkName(defaultColumns.deleteColumn, type));
    });

    var errTimeOut;
    $('#btnGenerate').on('click', function () {
        var data = $.serializeObj('.main-config');
        var columns = $.serializeTableObj(".table tr[data-column=1]");
        var indexes = $.serializeTableObj(".table tr[data-column=2]");
        data.columns = columns;
        data.indexes = indexes;
        $.post("createtable/?handler=generate", JSON.stringify(data), res => {
            console.log(res);
            if (res.code === 0 || res.code === "Success") {
                var content = '';
                var dcontent = '<div class="item"><div class="oper">';
                var item = res.data;
                content += '<div class="item">';
                content +=
                    '<div class="oper"><a class="copy" data-toggle="tooltip" title="代码已复制" href="javascript:;" data-clipboard-action="copy" data-clipboard-text="' +
                    item.sourceContent +
                    '">Copy</a><a class="download" title="点击下载代码文件" href="/?handler=Download&fileName=' +
                    item.fileLink +
                    '&type=1" target="_blank">Download</a></div>';
                content += '<div class="content">' + item.htmlContent + '</div>';
                content += '</div>';
                dcontent +=
                    '<a class="download" title="点击下载代码文件" href="/?handler=Download&fileName=' +
                    item.fileLink +
                    '&type=1" target="_blank">' +
                    item.fileLink +
                    '</a>';
                dcontent += '</div></div>'; // end item
                content = dcontent + content;
                $('#result').html(content);
                var clipboard = new ClipboardJS('.copy');
                clipboard.on('success',
                    function (e) {
                        console.info('Action:', e.action);
                        //console.info('Text:', e.text);
                        //console.info('Trigger:', e.trigger);
                        e.clearSelection();
                        $(e.target).tooltip();
                    });
                clipboard.on('error',
                    function (e) {
                        console.error('Action:', e.action);
                        console.error('Trigger:', e.trigger);
                    });
                saveCache();
            } else {
                $("#btnGenerate").attr("data-content", res.message);
                $("[data-toggle='popover']").popover('hide');
                $("[data-toggle='popover']").popover('show');
                $("#result").html("");
                clearTimeout(errTimeOut);
                errTimeOut = setTimeout(() => {
                    $("[data-toggle='popover']").popover('hide');
                }, 5000);
            }
        });
    });

    $("select[name=DbType]").on('change', e => {
        var that = $(e.target);
        setCurrentDbType(parseInt(that.val()));
    });

    $("#btnShowUpload").click(e => {
        showUpload('模板上传', res => console.log("上传成功"));
    });

    // 设置当前数据库类型
    var type = $("select[name=DbType]").val();
    setCurrentDbType(parseInt(type));
});

$("select[name=DefaultColumnNameType]").on('change', e => {
    var that = $(e.target);
    //console.log(that.val())
});

function setCurrentDbType(type, onlySet) {
    $.get('createtable/?handler=settingconfig&dbType=' + type, {}, res => {
        if (onlySet) {
            setConfig();
            return;
        }
        if (res.code === "Success") {
            setDefaultConnectInfo(type, res.data);
        } else {
            setDefaultConnectInfo(type);
        }
        setConfig(); // 同时设置好数据类型
    });
}

function saveCache() {
    Config.save(0, '.main-config', o => Config.dbTypes[o.DbType] + '|' + o.ServerName + '|' + o.Port + '|' + o.Database);
}

// 设置当前配置
function setConfig() {
    var data = $.serializeObj(".main-config");
    $.post("createtable/?handler=setconfig", JSON.stringify(data), res => {
        if (res.code === 0 || res.code === "Success") {
            dataTypes = res.data;
            // 注册新行动作
            regRowAction();
        } else {
            $("#btnSetConfig").attr("data-content", res.message);
            $("[data-toggle='popover']").popover('hide');
            $("[data-toggle='popover']").popover('show');
            setTimeout(() => {
                $("[data-toggle='popover']").popover('hide');
            }, 5000);
        }
    });
}

function setDefaultConnectInfo(dbType, data) {
    var isDefault = data === undefined;
    switch (dbType) {
        case 0: // sqlserver
            setValue('Database', isDefault ? 'LanGuo' : data.database);
            setValue('UserId', isDefault ? 'sa' : data.userId);
            setValue('Password', isDefault ? 'DX.net123!@#' : data.password);
            setValue('ServerName', isDefault ? 'test-db.xianshuabao.com' : data.serverName);
            setValue('TableName', isDefault ? 'romOrder2' : data.tableName);
            setValue('Port', isDefault ? '1433' : data.port);
            setValue('Description', isDefault ? '' : data.description);
            break;
        case 1: // mysql
            setValue('Database', isDefault ? 'demo' : data.database);
            setValue('UserId', isDefault ? 'root' : data.userId);
            setValue('Password', isDefault ? '1234' : data.password);
            setValue('ServerName', isDefault ? 'localhost' : data.serverName);
            setValue('TableName', isDefault ? 'user' : data.tableName);
            setValue('Port', isDefault ? '3306' : data.port);
            setValue('Description', isDefault ? '' : data.description);
            break;
        case 2: // sqlite
            setValue('Database', isDefault ? '忽略' : data.database);
            setValue('UserId', isDefault ? '忽略' : data.userId);
            setValue('Password', isDefault ? '忽略' : data.password);
            setValue('ServerName', isDefault ? 'D:\\DB\\sqlite\\demo.db' : data.serverName);
            setValue('TableName', isDefault ? 'person' : data.tableName);
            setValue('Port', isDefault ? '0' : data.port);
            setValue('Description', isDefault ? '' : data.description);
            break;
        case 3: // postgreSQL
            setValue('Database', isDefault ? 'demodb' : data.database);
            setValue('UserId', isDefault ? 'postgres' : data.userId);
            setValue('Password', isDefault ? '1234' : data.password);
            setValue('ServerName', isDefault ? 'localhost' : data.serverName);
            setValue('TableName', isDefault ? 'user' : data.tableName);
            setValue('Port', isDefault ? '5432' : data.port);
            setValue('Description', isDefault ? '' : data.description);
            break;
        default:
            setValue('Database', '');
            setValue('UserId', '');
            setValue('Password', '');
            setValue('ServerName', '');
            setValue('TableName', '');
            setValue('Port', '');
            setValue('Description', '');
            break;
    }
}

// type:0 input 1:select
// name: 对应名称，value:对应值
function setValue(name, value, type = 0) {
    var sType = type === 0 ? 'input' : 'select';
    name = sType + "[name=" + name + "]";
    $(name).val(value);
}

function loadDefaultColumns() {
    $.get('createtable/?handler=defaultColumns',
        res => {
            if (res.code === 0 || res.code === "Success") {
                defaultColumns = res.data;
            }
        });
}

function valueItem(item, name) {
    var itemVal = itemValue(item, name);
    if (undefined === itemVal || itemVal === '') {
        return '';
    }
    if (typeof (itemVal) === 'number' && itemVal === 0) {
        return '';
    }
    if (typeof (itemVal) === 'boolean' && itemVal === true) {
        return 'checked="checked"';
    }
    return 'value="' + itemVal + '"';
}

function itemValue(item, name) {
    if (item === undefined) {
        return undefined;
    }
    return item[name];
}

// 添加默认列
function addDefaultColumnRow(items) {
    console.log(defaultColumns);
    for (var item of items) {
        addRow(item);
    }
}

// 新增一行
function addRow(item) {
    var content = '\
            <tr class="row" data-column="1">\
                <td class="col-md-2"><input name="ColumnName" class="form-control" placeholder="列名" '+ valueItem(item, 'name') + ' /></td>\
                <td class="col-md-1"><input name="DataType" class="form-control" placeholder="数据类型" '+ valueItem(item, 'dataType') + '  /></td>\
                <td class="col-md-1"><input name="Length" type="text" class="form-control" placeholder="长度,精度" title="长度,精度" '+ valueItem(item, 'length') + ' /></td>\
                <td class="col-md-1"><input type="checkbox" name="AllowNulls" class="form-control" placeholder="是否可空" /> </td>\
                <td class="col-md-1"><input type="checkbox" name="PrimaryKey" class="form-control" placeholder="主键" /></td>\
                <td class="col-md-1"><input name="DefaultValue" class="form-control" placeholder="默认值" '+ valueItem(item, 'defaultValue') + '/></td>\
                <td class="col-md-1"><input name="IncrementValue" type="number" class="form-control" placeholder="自增量" /></td>\
                <td class="col-md-1"><input type="checkbox" name="Unsigned" class="form-control" placeholder="无符号" '+ valueItem(item, 'unsigned') + ' /> </td>\
                <td class="col-md-2"><input name="Remark" class="form-control" placeholder="备注" '+ valueItem(item, 'remark') + '/></td>\
                <td class="col-md-1">\
                    <button type="button" class="close float-left" aria-label="关闭">\
                        <span aria-hidden="true">&times;</span>\
                    </button>\
                </td>\
            </tr>';
    $(".pd").parent().append(content);
    regRowAction();
}

// 注册新行动作
function regRowAction() {
    // 先取消，再注册
    $("input[name=DataType]").typeahead('destroy');
    $("input[name=Remark]").unbind("keydown");
    $("td .close").unbind("click");

    // 添加类型自动提示
    //console.log(dataTypes)
    $("input[name=DataType]").typeahead({
        source: dataTypes,
        autoSelect: true,
        displayText: item => item.text,
        fitToElement: true
    });

    // 注册回车 添加新行
    $("input[name=Remark]").on("keydown", e => {
        if (e.keyCode === 13) {
            if (e.ctrlKey) { // ctrl+ enter 此时为最后一行
                curColumns = $.serializeNameArray(".tb-column", "ColumnName", true);
                regIndexRow(); // 注册索引行
                focusIndex();
            } else {
                addRow();
            }
        }
    });

    // 注册点击 删除行
    $("td .close").on("click", e => {
        var length = $("td .close").length || 0;
        if (length <= 1) {
            return;
        }

        var that = $(e.target);
        that.parent().parent().parent().remove();
    });

    // 选择到最新一行的 Name
    var $name = $('input[name=ColumnName]').last();
    $name.focus();
    curColumns = $.serializeNameArray(".tb-column", "ColumnName", true);
    regIndexRow(); // 注册索引行

    $("#tdata").tableDnD({
        onDragClass: 'highlight',
        onDrop: (table, row) => {
            console.log(row)
        }
    });
}

var curColumns = []; // 当前列数组

function addIndex() {
    var content = '<tr class="row" data-column="2"> \
        <td class="col-md-2" ><input name="IndexName1" class="form-control" placeholder="列名1" /></td> \
        <td class="col-md-2"><input name="IndexName2" class="form-control" placeholder="列名2" /></td> \
        <td class="col-md-2"><input name="IndexName3" class="form-control" placeholder="列名3" /></td> \
        <td class="col-md-2"><input name="IndexName4" class="form-control" placeholder="列名4" /></td> \
        <td class="col-md-2"><input name="IndexName5" class="form-control" placeholder="列名5" /></td> \
        <td class="col-md-1"><input name="UniqueIndex" type="checkbox" class="form-control" placeholder="唯一索引" title="是否唯一索引" /></td> \
        <td class="col-md-1"> \
        <button type="button" class="close float-left" aria-label="关闭"> \
        <span aria-hidden="true">&times;</span> \
        </button>\
        </td>\
        </tr >';
    $('.pad').parent().append(content);
    regIndexRow(true);
}

// 注册当前索引行
function regIndexRow(isNewRow) {
    // 取消注册
    var i;
    for (i = 1; i <= 5; ++i) {
        $("input[name=IndexName" + i + "]").typeahead('destroy');
        $("input[name=IndexName" + i + "]").unbind("keydown");
    }
    $("input[name=UniqueIndex]").unbind("keydown");

    // 注册事件
    for (i = 1; i <= 5; ++i) {
        $("input[name=IndexName" + i + "]").typeahead({
            source: curColumns,
            autoSelect: true,
            displayText: item => item,
            fitToElement: true
        });

        $("input[name=IndexName" + i + "]").on("keydown", e => {
            if (e.keyCode === 13) {
                addIndex();
            }
        });
    }

    $("input[name=UniqueIndex]").on("keydown", e => {
        if (e.keyCode === 13) {
            addIndex();
            e.preventDefault();
        }
    });


    // 注册点击 删除行
    $("td .close").on("click", e => {
        var length = $("td .close").length || 0;
        if (length <= 1) {
            return;
        }

        var that = $(e.target);
        that.parent().parent().parent().remove();
    });

    isNewRow = !!isNewRow;
    if (isNewRow) {
        // 选择到最新一行的 IndexName1
        focusIndex();
    }
}

//  聚焦到索引 ctrl+enter
function focusIndex() {
    var $name = $('input[name=IndexName1]').last();
    $name.focus();
}

// 增加默认列表命名格式
 function DefaultColumnNameOper() {
    /**
     * 按选择的命名格式修改name 
     * @param {any} items
     * @param {any} type 0,1,2,3（按配置原样，1首字母大写驼峰命名，2首字母小写驼峰命名，3蛇形命名）
     * @returns
     */
     this.checkName = (items, type) => {
         if (items === undefined || items.length === 0) {
             return items;
         }
         if (type === 0) {
             return items;
         }
         for (var i = 0; i < items.length; ++i) {
             var item = items[i];
             var name = itemValue(item, 'name');
             if (name === undefined) {
                 continue;
             }
             if (type === 1) {
                 name = this.camel(name, true);
             } else if (type === 2) {
                 name = this.camel(name, false);
             } else if (type === 3) {
                 name = this.snake(name);
             } else {
                 // nothing to do.
             }
             console.log('the name is ' + name)
             item['name'] = name;
         }
         return items;
     };
     this.wordCamelUpper = str => {
         if (str === undefined || str.length === 0) {
             return str;
         }
         str = str.trim();
         if (str.length == 1) {
             return str.toUpperCase();
         }
         return str.substring(0, 1).toUpperCase() + str.substring(1);
     };
         this.wordCamelLower = str => {
             if (str === undefined || str.length === 0) {
                 return str;
             }
             str = str.trim();
             if (str.length == 1) {
                 return str.toLowerCase();
             }
             return str.substring(0, 1).toLowerCase() + str.substring(1);
         };
     this.camel = (name, isUpper) => {
         var that = this;
         if (name === undefined || name.length === 0) {
             return name;
         }
         name = name.trim();
         if (name.length === 1) {
             return isUpper ? that.wordCamelUpper(name) : that.wordCamelLower(name);
         }
         var index = name.indexOf('_');
         if (index === -1) {
             return isUpper ? that.wordCamelUpper(name) : that.wordCamelLower(name);
         }
         var items = name.split('_');
         var str = '';
         for (var s of items) {
             var tmp = '';
             if (str === '') {
                 if (isUpper) {
                     tmp = that.wordCamelUpper(s);
                 } else {
                     tmp = s;
                 }
             } else {
                 tmp = that.wordCamelUpper(s);
             }

             str += tmp;
         }
         return str;
     };
     this.snake = name => {
         var that = this;
         if (name === undefined || name.length === 0) {
             return name;
         }
         if (name.indexOf('_') != -1) {
             return name;
         }
         name = name.trim();
         if (name.length === 1) {
             return name.wordCamelLower();
         }
         var str = '';
         for (var i = 0; i < name.length; ++i) {
             var ch = name[i];
             if (that.isUpper(ch) && str !== '') {
                 str += '_';
             }
             str += ('' + ch).toLowerCase();
         }
         return str;
     };
     this.isUpper = ch => {
         if (ch === undefined) {
             return false;
         }
         return ch >= 'A' && ch <= 'Z';
     };
     this.isLower = ch => {
         if (ch === undefined) {
             return false;
         }
         return ch >= 'a' && ch <= 'z';
     };
}
//window.DemoName = defaultColumnNameOp;